package com.gxa.jjty.admin.controller;

import com.github.pagehelper.PageInfo;
import com.gxa.jjty.admin.schedule.ChangeOrderState;
import com.gxa.jjty.admin.service.PhyUserService;
import com.gxa.jjty.admin.service.TorderService;
import com.gxa.jjty.core.common.ExceptionCode;
import com.gxa.jjty.core.common.JsonResult;
import com.gxa.jjty.core.exception.BusinessException;
import com.gxa.jjty.core.pojo.OrderoRecord;
import com.gxa.jjty.core.pojo.PhyUser;
import com.gxa.jjty.core.pojo.Torder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import io.swagger.v3.oas.annotations.parameters.RequestBody;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wanjun
 * @version 1.0
 * @date 2021/12/1 20:22
 */
@Log4j2
@Api(tags = "后台订单接口")
@RestController
@RequestMapping("/order")
@Validated
public class TorderController {

    @Autowired
    private PhyUserService phyUserService;
    @Autowired
    private TorderService torderService;
    @Autowired
    ChangeOrderState changeOrderState;
    private static final String TORDER_NUM_PRE="CJR";

    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderAddress",value = "服务地址(必须)",required = true),
            @ApiImplicitParam(name = "orderUser",value = "姓名(必须)",required = true),
            @ApiImplicitParam(name = "orderPhone",value = "电话(必须)",required = true),
            @ApiImplicitParam(name = "cjrId",value = "(必须)",required = true),
            @ApiImplicitParam(name = "serveType",value = "服务类型(必须)",required = true),
            @ApiImplicitParam(name = "orderPrice",value = "订单价格(必须)",required = true),
            @ApiImplicitParam(name = "orderRemark",value = "订单备注(可选)"),
            @ApiImplicitParam(name = "bookTime",value = "预约时间(可选)")
            })
    @ApiOperation("后台添加订单的方法")
    @PostMapping("/insertOrder")
    public Map<String,Object> addOrder(@RequestBody @ApiIgnore Torder torder){

        //设置订单生成时间
        torder.setOrderTime(new Date());
        //初始状态待付款
        torder.setOrderState("待付款");
        //订单编号生成
        /////////////////////////////////////////////
        //获得一个3位随机数
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < 3; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        //生成一个时间字符串:年月日时分秒毫秒
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(timestamp);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format = simpleDateFormat.format(timestamp);
        //前缀+时间+随机数生成订单编码
        torder.setOrderNumber(TORDER_NUM_PRE+format+code.toString());
        /////////////////////////////////////////////
        System.out.println(torder);
        torderService.insert(torder);
        return new JsonResult("1","成功","").getDataMap();
    }

    @ApiOperation("后台条件查询订单列表")
    @PostMapping("/selectOrderByField")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "from", value = "开始时间(可选)"),
            @ApiImplicitParam(name = "to", value = "结束时间(可选)"),
            @ApiImplicitParam(name = "orderNumber", value = "编号(可选)"),
            @ApiImplicitParam(name = "orderUser", value = "用户(可选)"),
            @ApiImplicitParam(name = "phyName", value = "陪护员(可选)"),
            @ApiImplicitParam(name = "orderState", value = "状态(可选)"),
            @ApiImplicitParam(name = "page", value = "页码(必须)",required = true),
            @ApiImplicitParam(name = "size", value = "每页显示条数(必须)",required = true)

    })
    public Map<String,Object> selectOrderByField(Date from,Date to,Integer page,Integer size,
                                                 String orderNumber,String orderUser,String phyName,String orderState) throws IllegalAccessException {

        System.out.println("=================================");
        System.out.println(from);
        System.out.println(to);
        System.out.println(page);
        System.out.println(size);
        Torder torder = new Torder();
        torder.setOrderNumber(orderNumber);
        torder.setOrderUser(orderUser);
        torder.setPhyName(phyName);
        torder.setOrderState(orderState);
        PageInfo<Torder> torderPageInfo = torderService.selectOrderByField(from, to, torder, page, size);
        return new JsonResult("1","成功",torderPageInfo).getDataMap();

    }



    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId",value = "订单id(必须)",required = true),
            @ApiImplicitParam(name = "operateUser", value = "操作人名字(必须)",required = true),
            @ApiImplicitParam(name = "orderAddress",value = "服务地址(可选,服务开始前可修改)"),
            @ApiImplicitParam(name = "serveType",value = "服务类型(可选,服务开始前可修改)"),
            @ApiImplicitParam(name = "orderPrice",value = "订单价格(可选,待付款才能改)"),
            @ApiImplicitParam(name = "orderRemark",value = "订单备注(可选,什么状态都能改)")

    })
    @ApiOperation("后台管理员修改订单")
    @PostMapping("/updateOrder")
    public Map<String,Object> updateOrder(Long orderId,String operateUser,String orderAddress,
              String serveType,Double orderPrice,String orderRemark) throws Exception {


        //操作记录的对象
        OrderoRecord orderoRecord = new OrderoRecord();
        orderoRecord.setOrderId(orderId);
        orderoRecord.setOperateContent("修改订单");
        orderoRecord.setOperateRemark(orderRemark);
        orderoRecord.setOperateTime(new Date());
        orderoRecord.setOperateUser(operateUser);


        Torder torder1 = torderService.selectById(orderId);
        String orderState = torder1.getOrderState();

        //待付款可以改价格
        if(!orderState.equals("待付款")&&orderPrice!=null){
            throw new BusinessException(ExceptionCode.ERROR);
        }
        //判断哪些状态的订单可以修改
        if(!orderState.equals("待付款")&&!orderState.equals("等待系统分配")&&!orderState.equals("陪护员已接单")&&!orderState.equals("待接单")&&
                (orderAddress!=null||serveType!=null)){
            throw new BusinessException(ExceptionCode.ERROR);
        }
        //什么状态都可以该备注
        torder1.setOrderAddress(orderAddress);
        torder1.setServeType(serveType);
        torder1.setOrderPrice(orderPrice);
        torder1.setOrderRemark(orderRemark);
        torderService.updateByIdAndRecord(torder1,orderoRecord);

        return new JsonResult("1","成功","").getDataMap();
    }





    @ApiOperation("后台查询全部订单(逆序,分页)")
    @PostMapping("/selectAllOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码",required = true),
            @ApiImplicitParam(name = "size", value = "每页显示条数",required = true)
    })
    public Map<String,Object> selectAllOrder( Integer page, Integer size) throws Exception {
        //筛选超时订单,再查询
        changeOrderState.changeAllOverTimeOrderState();
        PageInfo<Torder> torderPageInfo = torderService.selectAllOrder(page, size);
        return new JsonResult("1","成功",torderPageInfo).getDataMap();
    }



    @ApiOperation("后台取消订单")
    @PostMapping("/cancelOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id",required = true),
            @ApiImplicitParam(name = "cancelRemark", value = "取消原因",required = true),
            @ApiImplicitParam(name = "cancelFrom", value = "取消来源,0:付款超时,1:平台,2:陪护员,3:客户",required = true),
            @ApiImplicitParam(name = "operateUser", value = "操作人名字(必须)",required = true)
    })
    public Map<String,Object> cancelOrder(Long orderId,String cancelRemark,
           Integer cancelFrom,String operateUser) throws Exception{
        Torder torder1 = torderService.selectById(orderId);
        String orderState = torder1.getOrderState();

        //操作记录的对象
        OrderoRecord orderoRecord = new OrderoRecord();
        orderoRecord.setOrderId(orderId);
        orderoRecord.setOperateContent("取消订单");
        orderoRecord.setOperateRemark(cancelRemark);
        orderoRecord.setOperateTime(new Date());
        orderoRecord.setOperateUser(operateUser);


        //未付款直接取消,取消原因
        if(orderState.equals("待付款")){
            torder1.setOrderState("已取消");
            torder1.setCancelFrom(cancelFrom);
            torder1.setCancelRemark(cancelRemark);
            torder1.setCancelTime(new Date());
            torderService.updateByIdAndRecord(torder1,orderoRecord);
            return new JsonResult("1","成功","").getDataMap();
        }

        //已完成订单取消抛出非法操作
        if(!orderState.equals("等待系统分配")&&!orderState.equals("陪护员已接单")&&!orderState.equals("服务中")){
            throw new BusinessException(ExceptionCode.ERROR);
        }

        //付款未完成订单,取消状态变为退款中,退款原因
        torder1.setOrderState("退款中");
        torder1.setRefundState("待处理");
        torder1.setRefundOrder("退款订单");
        torder1.setCancelFrom(cancelFrom);
        torder1.setCancelRemark(cancelRemark);
        torder1.setCancelTime(new Date());
        torderService.updateByIdAndRecord(torder1,orderoRecord);
        return new JsonResult("1","成功","").getDataMap();
    }



    @ApiOperation("后台转单")
    @PostMapping("/transgerOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id",required = true),
            @ApiImplicitParam(name = "transgerRemark", value = "转单备注(可选)"),
            @ApiImplicitParam(name = "phyId", value = "陪护人id(必须)",required = true),
            @ApiImplicitParam(name = "operateUser", value = "操作人名字(必须)",required = true)
    })
    public Map<String,Object> transgerOrder(Long orderId,String transgerRemark,
        Long phyId,String operateUser) throws Exception{

        Torder torder = new Torder();
        torder.setOrderId(orderId);
        torder.setTransgerRemark(transgerRemark);
        torder.setPhyId(phyId);


        //等待系统分配/陪护员已接单两种状态可以转单
        Torder torder1 = torderService.selectById(torder.getOrderId());
        if(!torder1.getOrderState().equals("等待系统分配")&&!torder1.getOrderState().equals("陪护员已接单")){
            throw new BusinessException(ExceptionCode.ERROR);
        }

        //操作记录的对象
        OrderoRecord orderoRecord = new OrderoRecord();
        orderoRecord.setOrderId(orderId);
        orderoRecord.setOperateContent("转单");
        orderoRecord.setOperateRemark(transgerRemark);
        orderoRecord.setOperateTime(new Date());
        orderoRecord.setOperateUser(operateUser);

        //修改订单记录,同时添加操作记录
        torderService.updateByIdAndRecord(torder,orderoRecord);
        return new JsonResult("1","成功","").getDataMap();
    }



    @ApiOperation("后台查询空闲状态的陪护员")
    @PostMapping("/freePhy")
    public Map<String,Object> freePhy(){
        //得到所有的陪护员
        List<PhyUser> allPhyUser = phyUserService.selectAll();
        //创建一个List存放正在服务的陪护员
        List<PhyUser>  phyUserList =new ArrayList<>();
        Torder torder = new Torder();
        torder.setOrderState("服务中");
        List<Torder> select = torderService.select(torder);
            for (Torder torder1 : select) {
                PhyUser phyUser1 = phyUserService.selectById(torder1.getPhyId());
                allPhyUser.remove(phyUser1);
            }


        return new JsonResult("1","成功",allPhyUser).getDataMap();

    }

    /*@ApiOperation("!!!勿用,查询某个用户的订单(逆序)")
    @PostMapping("/selectOrderByUser")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cjrId", value = "残疾人id(必须int)",required = true)
    })
    public Map<String,Object> selectOrderByUser(@ApiIgnore @RequestBody Torder torder) throws Exception {
        //筛选超时订单,再查询
        changeOrderState.changeAllOverTimeOrderState();
        List<Torder> select = torderService.selectDesc(torder);
        return new JsonResult("1","成功",select).getDataMap();
    }



    @ApiOperation("!!!勿用,支付--支付金额,支付方式存储")
    @PostMapping("/addPayMassage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id(必须)",required = true),
            @ApiImplicitParam(name = "payType", value = "支付方式(必须)",required = true),
            @ApiImplicitParam(name = "payPrice", value = "支付金额(必须)",required = true)
    })
    public Map<String,Object> addPayMassage(@ApiIgnore @RequestBody Torder torder) throws IllegalAccessException {
        torder.setOrderState("等待系统分配");
        torder.setPayTime(new Date());
        torderService.updateById(torder);

        return new JsonResult("1","成功","").getDataMap();
    }


    @ApiOperation("!!!勿用,接单--存储陪护人姓名,id")
    @PostMapping("/addPhrMassage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id(必须)",required = true),
            @ApiImplicitParam(name = "phyName", value = "陪护人姓名(必须)",required = true),
            @ApiImplicitParam(name = "phyId", value = "陪护人id(必须)",required = true)
    })
    public Map<String,Object> addPhrMassage(@ApiIgnore @RequestBody Torder torder) throws Exception {
        torder.setAcceptTime(new Date());
        torder.setOrderState("陪护员已接单");
        torderService.updateById(torder);
        return new JsonResult("1","成功","").getDataMap();

    }


    @ApiOperation("!!!勿用,开始服务")
    @PostMapping("/startServe")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id(必须)",required = true),
    })
    public Map<String,Object> startServe(@ApiIgnore @RequestBody Torder torder) throws IllegalAccessException {
        torder.setServeTime(new Date());
        torder.setOrderState("服务中");
        torderService.updateById(torder);
        return new JsonResult("1","成功","").getDataMap();
    }



    @ApiOperation("!!!勿用,确认完成服务")
    @PostMapping("/finishServe")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id(必须)",required = true),
    })
    public Map<String,Object> finishServe(@ApiIgnore @RequestBody Torder torder) throws IllegalAccessException {
        torder.setServfinishTime(new Date());
        torder.setOrderState("已完成");
        torderService.updateById(torder);
        return new JsonResult("1","成功","").getDataMap();
    }






    @ApiOperation("!!!勿用,同意退款")
    @PostMapping("/agreeRefund")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id(必须)",required = true)
    })
    public Map<String,Object> agreeRefund(@ApiIgnore @RequestBody Torder torder) throws Exception{

        Torder torder1 = torderService.selectById(torder.getOrderId());
        String orderState = torder1.getOrderState();

        //只能对退款中的订单操作
        if(!orderState.equals("退款中")){
            throw new BusinessException(ExceptionCode.ERROR);
        }

        torder1.setOrderState("退款成功");
        torderService.updateById(torder1);
        return new JsonResult("1","成功","").getDataMap();
    }




    @ApiOperation("!!!勿用,拒绝退款")
    @PostMapping("/refuseRefund")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id(必须)",required = true)
    })
    public Map<String,Object> refuseRefund(@ApiIgnore @RequestBody Torder torder) throws Exception{

        Torder torder1 = torderService.selectById(torder.getOrderId());
        String orderState = torder1.getOrderState();

        //只能对退款中的订单操作
        if(!orderState.equals("退款中")){
            throw new BusinessException(ExceptionCode.ERROR);
        }

        torder1.setOrderState("退款失败");
        torderService.updateById(torder1);
        return new JsonResult("1","成功","").getDataMap();
    }
*/

    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "订单编码", required = true)
    })
    @ApiOperation("订单详情")
    @PostMapping("/getOrderDetail")
    public Map<String,Object> getOrderDetail(String  orderNumber){
        List orderDetail = torderService.getOrderDetail(orderNumber);
        return new JsonResult("1","成功",orderDetail).getDataMap();
    }


}
